package com.cooperate.fly.controller;

import com.cooperate.fly.bo.Field;
import com.cooperate.fly.service.buildDB.BuildFieldService;
import com.cooperate.fly.util.SystemConstant;
import com.cooperate.fly.web.Result;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * Created by Stellar_Lee on 2016/5/4.
 */
@Controller
@RequestMapping("/field")
@SessionAttributes(SystemConstant.USER_SESSION_KEY)
public class FieldController {
    @Autowired
    private BuildFieldService buildFieldService;


    /**
     * get all field belong to this database
     *
     * @param did
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/loadField", produces = "application/json;charset=utf-8")
    public String loadField(int did) {
        return buildFieldService.loadField(did);
    }

    @ResponseBody
    @RequestMapping("/create")
    public Result addField(Field field) {
        return buildFieldService.createFieldNode(field);
    }

    @ResponseBody
    @RequestMapping("/create3Matrix")
    public Result create3Matrix(int fid,String xName,String xTitle,String yName,String yTitle,String zName){
        buildFieldService.create3Matrix(fid,xName,xTitle,yName,yTitle,zName);
        return new Result();
    }
    @ResponseBody
    @RequestMapping("/edit")
    public Result editField(Field field) {
        return buildFieldService.updateFieldNode(field);
    }

    @ResponseBody
    @RequestMapping("/destroy")
    public Result deleteField(int id) {
        return buildFieldService.deleteFieldNodeById(id);
    }

    @ResponseBody
    @RequestMapping(value="/download",method = RequestMethod.GET)
    public ResponseEntity<byte[]> download(@RequestParam(value="schemaId", required=true) int schemaId,int fieldId) throws Exception{
        HttpHeaders headers=new HttpHeaders();
        File file=buildFieldService.downloadFields(schemaId,fieldId);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        String name=file.getName();
        headers.setContentDispositionFormData("attachment",name);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
    }

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public void uploadFile(@RequestParam(value="schemaId", required=true) int schemaId,int fieldId,MultipartHttpServletRequest multipartRequest,
                             HttpServletRequest request,HttpServletResponse response) throws IOException{
        response.setContentType("text/html;charset=UTF-8");
        Result result = new Result();
        try{
            for(Iterator it = multipartRequest.getFileNames();it.hasNext();){
                String key = (String)it.next();
                MultipartFile file = multipartRequest.getFile(key);
                if(!file.isEmpty()){
                    String filePath=request.getSession().getServletContext().getRealPath("/") + "upload/";
                    File pathFile=new File(filePath);
                    if(!pathFile.exists()){
                        pathFile.mkdirs();
                    }
                    filePath+=file.getOriginalFilename();
                    File tempFile=new File(filePath);
                    if(!tempFile.exists()){
                        file.transferTo(tempFile);
                    }
                    InputStreamReader reader=new InputStreamReader(new FileInputStream(filePath),"utf8");
                    BufferedReader br=new BufferedReader(reader);
                    StringBuffer sb=new StringBuffer();
                    String data=null;
                    while((data=br.readLine())!=null){
                        sb.append(data);
                    }
                    if(sb.toString()!=null&&sb.toString()!=""){
                        result=buildFieldService.freshData(sb.toString(),schemaId,fieldId);
                    }
                    if(tempFile.exists()){
                        tempFile.delete();
                    }
                    reader.close();
                    br.close();
                }
            }
            response.getWriter().print(result.getData());
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestMapping("/getRemark3")
    public Result getRemark3(int id) {
        return buildFieldService.getRemark3(id);
    }

    @ResponseBody
    @RequestMapping("/getRemark1")
    public Result getRemark1(int id) {
        return buildFieldService.getRemark1(id);
    }

    @RequestMapping(value = "/{fieldId}", produces = "application/json;charset=utf-8",method = RequestMethod.GET,params = "action=get")
    @ResponseBody
    public String getField(@PathVariable int fieldId) {
        Map<String, String> maps = buildFieldService.loadPartField(fieldId);
        if(maps==null){
            return null;
        }
         return maps.get("fieldStr");
    }

    @ResponseBody
    @RequestMapping("/moveNode")
    public Result moveNode(int frontNodeId,int backNodeId){
        return buildFieldService.exchangeNode(frontNodeId, backNodeId);
    }

}
